import db from '../config/database.js'
import WechatPay from '../utils/wechatPay.js'
import {validateWechatConfig} from '../config/wechat.js'

/**
 * 创建支付订单
 */
export async function createPayment(req, res) {
  try {
    const {order_no, openid} = req.body

    // 验证参数
    if (!order_no) {
      return res.status(400).json({
        success: false,
        error: '缺少订单号'
      })
    }

    if (!openid) {
      return res.status(400).json({
        success: false,
        error: '缺少用户 openid'
      })
    }

    // 验证微信支付配置
    if (!validateWechatConfig()) {
      return res.status(500).json({
        success: false,
        error: '微信支付配置不完整，请联系管理员'
      })
    }

    // 查询订单信息
    const [orders] = await db.query('SELECT * FROM orders WHERE order_no = ?', [order_no])

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      })
    }

    const order = orders[0]

    // 检查订单状态
    if (order.status !== 'pending') {
      return res.status(400).json({
        success: false,
        error: '订单状态不正确'
      })
    }

    // 查询展览信息
    const [exhibitions] = await db.query('SELECT title FROM exhibitions WHERE id = ?', [order.exhibition_id])

    if (exhibitions.length === 0) {
      return res.status(404).json({
        success: false,
        error: '展览不存在'
      })
    }

    const exhibition = exhibitions[0]

    // 构建支付参数
    const paymentData = {
      body: `${exhibition.title} - 门票`, // 商品描述
      out_trade_no: order_no, // 商户订单号
      total_fee: Math.round(order.total_amount * 100), // 金额转换为分
      spbill_create_ip: req.ip || '127.0.0.1', // 终端IP
      openid: openid // 用户 openid
    }

    // 调用微信支付统一下单
    const result = await WechatPay.unifiedOrder(paymentData)

    if (result.success) {
      // 记录支付请求
      await db.query(
        'INSERT INTO payment_logs (order_no, openid, amount, status, created_at) VALUES (?, ?, ?, ?, NOW())',
        [order_no, openid, order.total_amount, 'pending']
      )

      res.json({
        success: true,
        data: result.data
      })
    } else {
      res.status(500).json({
        success: false,
        error: result.error
      })
    }
  } catch (error) {
    console.error('创建支付订单失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '创建支付订单失败'
    })
  }
}

/**
 * 支付回调通知
 */
export async function paymentNotify(req, res) {
  try {
    // 解析 XML 数据
    const data = WechatPay.xmlToObj(req.body)

    // 验证签名
    if (!WechatPay.verifyNotifySign(data)) {
      console.error('支付回调签名验证失败')
      return res.send(
        WechatPay.objToXml({
          return_code: 'FAIL',
          return_msg: '签名验证失败'
        })
      )
    }

    // 检查支付结果
    if (data.return_code === 'SUCCESS' && data.result_code === 'SUCCESS') {
      const orderNo = data.out_trade_no
      const transactionId = data.transaction_id

      // 查询订单
      const [orders] = await db.query('SELECT * FROM orders WHERE order_no = ?', [orderNo])

      if (orders.length === 0) {
        console.error('订单不存在:', orderNo)
        return res.send(
          WechatPay.objToXml({
            return_code: 'FAIL',
            return_msg: '订单不存在'
          })
        )
      }

      const order = orders[0]

      // 检查订单是否已支付
      if (order.status === 'paid') {
        // 已支付，直接返回成功
        return res.send(
          WechatPay.objToXml({
            return_code: 'SUCCESS',
            return_msg: 'OK'
          })
        )
      }

      // 更新订单状态
      await db.query('UPDATE orders SET status = ?, transaction_id = ?, paid_at = NOW() WHERE order_no = ?', [
        'paid',
        transactionId,
        orderNo
      ])

      // 更新支付日志
      await db.query('UPDATE payment_logs SET status = ?, transaction_id = ?, updated_at = NOW() WHERE order_no = ?', [
        'success',
        transactionId,
        orderNo
      ])

      console.log('订单支付成功:', orderNo)

      // 返回成功响应
      res.send(
        WechatPay.objToXml({
          return_code: 'SUCCESS',
          return_msg: 'OK'
        })
      )
    } else {
      // 支付失败
      console.error('支付失败:', data.err_code_des || data.return_msg)

      // 更新支付日志
      await db.query(
        'UPDATE payment_logs SET status = ?, error_msg = ?, updated_at = NOW() WHERE order_no = ?',
        ['failed', data.err_code_des || data.return_msg, data.out_trade_no]
      )

      res.send(
        WechatPay.objToXml({
          return_code: 'SUCCESS',
          return_msg: 'OK'
        })
      )
    }
  } catch (error) {
    console.error('处理支付回调失败:', error)
    res.send(
      WechatPay.objToXml({
        return_code: 'FAIL',
        return_msg: error.message || '处理失败'
      })
    )
  }
}

/**
 * 查询支付状态
 */
export async function queryPayment(req, res) {
  try {
    const {order_no} = req.params

    if (!order_no) {
      return res.status(400).json({
        success: false,
        error: '缺少订单号'
      })
    }

    // 验证微信支付配置
    if (!validateWechatConfig()) {
      return res.status(500).json({
        success: false,
        error: '微信支付配置不完整'
      })
    }

    // 查询微信支付订单状态
    const result = await WechatPay.queryOrder(order_no)

    if (result.success) {
      const {trade_state, trade_state_desc} = result.data

      // 如果支付成功，更新本地订单状态
      if (trade_state === 'SUCCESS') {
        await db.query('UPDATE orders SET status = ?, paid_at = NOW() WHERE order_no = ? AND status = ?', [
          'paid',
          order_no,
          'pending'
        ])
      }

      res.json({
        success: true,
        data: {
          trade_state,
          trade_state_desc
        }
      })
    } else {
      res.status(500).json({
        success: false,
        error: result.error
      })
    }
  } catch (error) {
    console.error('查询支付状态失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '查询支付状态失败'
    })
  }
}

/**
 * 申请退款
 */
export async function refundPayment(req, res) {
  try {
    const {order_no, refund_reason} = req.body

    if (!order_no) {
      return res.status(400).json({
        success: false,
        error: '缺少订单号'
      })
    }

    // 验证微信支付配置
    if (!validateWechatConfig()) {
      return res.status(500).json({
        success: false,
        error: '微信支付配置不完整'
      })
    }

    // 查询订单
    const [orders] = await db.query('SELECT * FROM orders WHERE order_no = ?', [order_no])

    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      })
    }

    const order = orders[0]

    // 检查订单状态
    if (order.status !== 'paid') {
      return res.status(400).json({
        success: false,
        error: '订单未支付或已退款'
      })
    }

    // 生成退款单号
    const refundNo = `RF${Date.now()}${Math.floor(Math.random() * 1000)}`

    // 构建退款参数
    const refundData = {
      out_trade_no: order_no,
      out_refund_no: refundNo,
      total_fee: Math.round(order.total_amount * 100),
      refund_fee: Math.round(order.total_amount * 100),
      refund_desc: refund_reason || '用户申请退款'
    }

    // 调用微信支付退款接口
    const result = await WechatPay.refund(refundData)

    if (result.success) {
      // 更新订单状态
      await db.query('UPDATE orders SET status = ?, refund_no = ?, refunded_at = NOW() WHERE order_no = ?', [
        'refunded',
        refundNo,
        order_no
      ])

      res.json({
        success: true,
        data: {
          refund_no: refundNo
        }
      })
    } else {
      res.status(500).json({
        success: false,
        error: result.error
      })
    }
  } catch (error) {
    console.error('申请退款失败:', error)
    res.status(500).json({
      success: false,
      error: error.message || '申请退款失败'
    })
  }
}
